package com.learn.concurrent.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * https://www.cnblogs.com/wyq1995/p/12253792.html
 */
public class Demo2 {

    public static void main(String[] args) throws InterruptedException {

        //创建锁对象
        ReentrantLock lock=new ReentrantLock();

        //创建条件变量
        Condition condition1=lock.newCondition();

        Condition condition2=lock.newCondition();

        //以下两个线程，都会获取锁和释放锁

        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread()+"开始等待");
                    Thread.sleep(8000);
                    condition1.await();
                    System.out.println(Thread.currentThread()+"等待结束");

                    System.out.println(Thread.currentThread()+"条件二开始唤醒其他线程");
                    Thread.sleep(5000);
                    condition2.signal();
                    System.out.println(Thread.currentThread()+"条件二唤醒其他线程结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        },"线程一");

        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    try {
                        System.out.println(Thread.currentThread()+"开始唤醒其他线程");
                        Thread.sleep(5000);
                        condition1.signal();
                        System.out.println(Thread.currentThread()+"唤醒其他线程结束");

                        System.out.println(Thread.currentThread()+"条件二开始等待");
                        condition2.await();
                        System.out.println(Thread.currentThread()+"条件二等待结束");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } finally {
                    lock.unlock();
                }
            }
        },"线程二");

        thread1.start();
        thread2.start();
    }

}
